//
//  HomePageTableViewController.m
//  InSuger
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 Dior_3g. All rights reserved.
//
#import "HomePageTableViewController.h" 
#import "HomePageCollectionDetailViewController.h"
#import "IconDetailsViewController.h"

@interface HomePageTableViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *tableArray;

@property(nonatomic, strong) NSMutableArray *collectionArray;
@property(nonatomic, strong) NSDictionary *collectionDic;
@property(nonatomic, strong) UICollectionView *collectionView;

@property(nonatomic, strong) UIView *headerView;

@property(nonatomic, strong) CarouselFigureView *scrollView;
@property(nonatomic, strong) NSMutableArray *scrollArray;
@property(nonatomic, strong) NSMutableArray *scrollPhototArray;

@property(nonatomic, assign) NSInteger num;
@property(nonatomic, strong) MBProgressHUD *progress;

@end

@implementation HomePageTableViewController


#pragma mark    检查网络状况
- (void)netWork{
    
    //      检测网络情况
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //      开始检测
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        self.num = status;
        
        self.progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        _progress.labelText = @"Loading...";
        
        _progress.mode = MBProgressHUDModeDeterminate;
        
        [self createData];
    }];
    
    [manager stopMonitoring];
 
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    [self createTableView];
    [self createCollectionView];
    
    [Save isHaveFolder];
    [self netWork];

    //      -----------------------------       下拉刷新    -----------------------------
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerData)];
    self.tableView.mj_header = header;
    
}

#pragma mark    下拉刷新
- (void)headerData {
    
    [self.tableView.mj_header beginRefreshing];
    [self createData];
    
}


#pragma mark    创建TableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(self.view);
        make.size.mas_equalTo(self.view);
        
    }];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[HomePageTableViewCell class] forCellReuseIdentifier:@"home"];
    self.tableView.rowHeight = self.tableView.frame.size.height / 4;
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT / 20, WIDTH, HEIGHT / 10 * 5)];
    self.tableView.tableHeaderView = self.headerView;

    //      夜间模式的颜色配置
    @weakify(self);
    [self addColorChangedBlock:^{
        @strongify(self);
        self.tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.tableView.nightSeparatorColor = UIColorFromRGB(0x313131);
        
        self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
        self.navigationController.navigationBar.normalBarTintColor = [UIColor redColor];
        
        self.collectionView.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.scrollView.nightBackgroundColor = UIColorFromRGB(0x343434);
    }];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"首页";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.tableView.backgroundColor = [UIColor whiteColor];

}

#pragma mark    创建ScrollView
- (void)createScrollView {
    
    self.scrollView = [[CarouselFigureView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 10 * 3.1) withArray:self.scrollPhototArray];
    [self.headerView addSubview:self.scrollView];
    self.scrollView.delegate = self;
    
}
#pragma mark    ScrollView的协议方法
- (void)pushVC:(NSInteger)tag {
    
    HomePageScrollViewModel *model = self.scrollArray[tag - 1000];
    NSLog(@"%@", model.type);
    if ([model.type isEqualToString:@"webview"]) {
        
        HomePageScrollWebViewController *webVC = [[HomePageScrollWebViewController alloc] init];
        [self.navigationController pushViewController:webVC animated:YES];
        webVC.model = model;
        
    } else {
        
        HomePageScrollDetailViewController *detailVC = [[HomePageScrollDetailViewController alloc] init];
        [self.navigationController pushViewController:detailVC animated:YES];
        detailVC.model = model;
    }
}


#pragma mark    创建CollectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 10 * 2.5, HEIGHT / 10 * 1.6);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(HEIGHT / 100, WIDTH / 25, HEIGHT / 100, 0);
    layout.minimumInteritemSpacing = WIDTH / 10;
    layout.minimumLineSpacing = HEIGHT / 40;

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT / 10 * 3.1, WIDTH, HEIGHT / 10 * 1.9) collectionViewLayout:layout];
    [self.collectionView registerClass:[HomePageCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.headerView addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.headerView.mas_top).with.offset(HEIGHT / 10 * 3.1);
        make.left.equalTo(self.headerView.mas_left).with.offset(0);
        make.bottom.equalTo(self.headerView.mas_bottom).with.offset(0);
        make.right.equalTo(self.headerView.mas_right).with.offset(0);
    }];

    self.collectionView.backgroundColor = [UIColor whiteColor];
}

#pragma mark    解析数据
- (void)createData {

    if (self.num == 1 || self.num == 2) {
        
        [AFN getdataWithString:@"http://open3.bantangapp.com/recommend/index?app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.1&page=0&pagesize=20&screensize=640&track_device_info=iPhone6%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7" block:^(id block) {
            
            self.collectionDic = block[@"data"];
            self.tableArray = [NSMutableArray array];
            self.tableArray = [HomePageTableViewModel baseModelByArr:self.collectionDic[@"topic"]];
            
            for (HomePageTableViewModel * model in self.tableArray) {
                if ([Save isHaveModelInTablePlist:model]) {
                    
                }else {
                    [Save saveModelToTablePlist:model];
                }
               
            }
            
            self.collectionArray = [NSMutableArray array];
            self.collectionArray = [HomePageCollectionViewModel baseModelByArr:self.collectionDic[@"entry_list"]];
            [self.collectionArray removeObjectAtIndex:0];
            
            for (HomePageCollectionViewModel *collection in self.collectionArray) {
                if ([Save isHaveModelInCollectionPlist:collection]) {
                    
                }else {
                    [Save saveModelToCollectionPlist:collection];
                }
            }
            
            NSArray *array = [HomePageScrollViewModel baseModelByArr:self.collectionDic[@"banner"]];
            self.scrollArray = [NSMutableArray array];
            self.scrollPhototArray = [NSMutableArray array];
            
            for (HomePageScrollViewModel *model in array) {
                [self.scrollPhototArray addObject:model.photo];
                [self.scrollArray addObject:model];
                if ([Save isHaveModelInScrollPlist:model]) {
                    
                }else {
                    [Save saveModelToScrollPlist:model];
                }
            }
            [self createScrollView];
            [self.collectionView reloadData];
            [self.tableView reloadData];
            [self.progress removeFromSuperview];
            [self.tableView.mj_header endRefreshing];
        }];
        
    }else {
        
        NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        NSString *tableDocPath = [sandBoxPath stringByAppendingPathComponent:@"Caches/table.plist"];
        NSString *collectionDocPath = [sandBoxPath stringByAppendingPathComponent:@"Caches/collection.plist"];
        NSString *scrollDocPath = [sandBoxPath stringByAppendingPathComponent:@"Caches/scroll.plist"];
        
        self.tableArray = [NSMutableArray array];
        self.tableArray = [NSKeyedUnarchiver unarchiveObjectWithFile:tableDocPath];
        
        self.collectionArray = [NSMutableArray array];
        self.collectionArray = [NSKeyedUnarchiver unarchiveObjectWithFile:collectionDocPath];

        self.scrollArray = [NSMutableArray array];
        self.scrollArray = [NSKeyedUnarchiver unarchiveObjectWithFile:scrollDocPath];

        self.scrollPhototArray = [NSMutableArray array];
        for (HomePageScrollViewModel *model in self.scrollArray) {

            [self.scrollPhototArray addObject:model.photo];
        }

        [self createScrollView];
        [self.collectionView reloadData];
        [self.tableView reloadData];
        [self.progress removeFromSuperview];
        [self.tableView.mj_header endRefreshing];
    }
}

#pragma mark    CollectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.collectionArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HomePageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];

    cell.model = self.collectionArray[indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
        

    HomePageCollectionDetailViewController *detailVC =[[HomePageCollectionDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    detailVC.model = self.collectionArray[indexPath.row];

    
}

#pragma mark    TableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomePageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"home" forIndexPath:indexPath];
    
    cell.model = self.tableArray[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomePageDetailViewController *detail = [[HomePageDetailViewController alloc] init];
    
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    
    detail.model = self.tableArray[indexPath.row];
    
}

#pragma mark    tableView滑动的时候隐藏navigationBar
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == self.tableView) {
        self.navigationController.hidesBarsOnSwipe = YES;
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
